package com.tz;

import com.tz.crm.BaseTest;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.sql.SQLException;
import java.util.EnumSet;

@PropertySource("classpath:app.properties")
public class InitTables extends BaseTest {

    @Autowired
    private Environment env;
    @Autowired
    private LocalSessionFactoryBean localSessionFactoryBean;

    private MetadataSources metadata;

    @BeforeClass
    public void setup() {
        Configuration configuration = localSessionFactoryBean.getConfiguration();

        metadata = new MetadataSources(
                new StandardServiceRegistryBuilder()
                        .applySettings(configuration.getProperties())
                        .build());
        localSessionFactoryBean.getMetadataSources()
                .getAnnotatedClasses()
                .forEach(entityClass -> {
                    metadata.addAnnotatedClass(entityClass);
                });
    }

    @Test(priority = 1)
    public void drop() throws IllegalAccessException, SQLException {
        SchemaExport schemaExport = new SchemaExport();
        schemaExport.drop(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());
    }

    @Test(priority = 2)
    public void createOnly() throws IllegalAccessException, SQLException {
        SchemaExport schemaExport = new SchemaExport();
        schemaExport.createOnly(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());
    }

}
